package de.bbl.android.tools;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import de.bbl.android.classes.*;

public class XmlParseGameDayTools {

	public static Match[] XmlParseGameDay(String xmlFilename) {
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	try {
    		DocumentBuilder db = dbf.newDocumentBuilder();
    		Document dom = db.parse(new File(xmlFilename));
    		Element docElement = dom.getDocumentElement();
    		NodeList nl = docElement.getElementsByTagName("key");
    		int postitionOfMatches = -1;
    		Node array = null;
    		
    		for (int i = 0; i < nl.getLength(); i++) {
    			String tempTextValue = nl.item(i).getTextContent().toString();
    			if (tempTextValue.equals("matches")) {    				
    				postitionOfMatches = i;
    				array = nl.item(i).getNextSibling();
    				while (array != null && !array.getNodeName().equals("array"))
    					array = array.getNextSibling();
    				
    				break;
    			}
    		}
    		if (postitionOfMatches == -1)
    			return null;
    		
    		return XmlParseMatches(array);    		
    		
    	} catch (Exception e) {
        	Tools.AppendToErrorFile(e.getMessage());
            // e.printStackTrace();
    	}
		return null;
	}
	
	public static Match[] XmlParseMatches(Node arrayNode) {
		
		ArrayList<Match> stringList = new ArrayList<Match>();
	    NodeList nl = ((Element) arrayNode).getElementsByTagName("dict");
	    for (int i = 0; i < nl.getLength(); i++) {
	    	if (nl.item(i).getParentNode().getNodeName().equals("array")) {
	    		stringList.add(XmlParseSingleMatch(nl.item(i)));
	    	}
	    }
	    Match[] retVal = new Match[stringList.size()];
	    stringList.toArray(retVal);
		return retVal;
	}
	
	public static Match XmlParseSingleMatch(Node matchNode) {
		String matchId = "";
		String matchdayNumber = "";
		String kickoff ="";
		String competitionId ="";
		String period ="";
		String homeTeamID ="";
		String homeTeamName ="";
		String homeTeamScore ="";
		String guestTeamID ="";
		String guestTeamName ="";
		String guestTeamScore ="";
		
		// hier sind wir im ArrayNode
		int childNodeCount = matchNode.getChildNodes().getLength();
		
		for (int i = 0; i < childNodeCount; i++) {
			Node currentChildNode = matchNode.getChildNodes().item(i);
			
			if (checkKey(currentChildNode, "matchId")){
				matchId = getNextValue(currentChildNode);
			}
			if (checkKey(currentChildNode, "matchdayNumber")){
				matchdayNumber = getNextValue(currentChildNode);
			}
			if (checkKey(currentChildNode, "kickoff")){
				kickoff = getNextValue(currentChildNode);
			}
			if (checkKey(currentChildNode, "competitionId")){
				competitionId = getNextValue(currentChildNode);
			}
			if (checkKey(currentChildNode, "period")){
				period = getNextValue(currentChildNode);
			}
			
			if (checkKey(currentChildNode, "home")){
				// jump to dict
				Node element = matchNode.getChildNodes().item(i + 2);
				int childNodeCountTeam = element.getChildNodes().getLength();

				NodeList nl = element.getChildNodes();
				for (int j = 0; j < childNodeCountTeam; j++) {
					element = nl.item(j);
					if (checkKey(element, "teamId")){
						homeTeamID = getNextValue(element);
					}
					if (checkKey(element, "teamName")){
						homeTeamName = getNextValue(element);
					}
					if (checkKey(element, "result")){
						homeTeamScore = getNextValue(element);
					}
				}
			}
			
			if (checkKey(currentChildNode, "guest")){
				// jump to dict
				Node element = matchNode.getChildNodes().item(i + 2);
				int childNodeCountTeam = element.getChildNodes().getLength();

				NodeList nl = element.getChildNodes();
				for (int j = 0; j < childNodeCountTeam; j++) {
					element = nl.item(j);
					if (checkKey(element, "teamId")){
						guestTeamID = getNextValue(element);
					}
					if (checkKey(element, "teamName")){
						guestTeamName = getNextValue(element);
					}
					if (checkKey(element, "result")){
						guestTeamScore = getNextValue(element);
					}
				}
			}
		
		}
		Match retValMatch = new Match(Integer.parseInt(matchId),Integer.parseInt(matchdayNumber),kickoff,Integer.parseInt(competitionId),period,new PlayingTeam(Integer.parseInt(homeTeamID), homeTeamName, Integer.parseInt(homeTeamScore)),new PlayingTeam(Integer.parseInt(guestTeamID), guestTeamName, Integer.parseInt(guestTeamScore)));
		return retValMatch;
	}
	
	public static boolean checkKey(Node node,String match) {
		return node.getNodeName().equals("key") && node.getTextContent().equals(match);		
	}
	
	public static String getNextValue(Node currentNode) {
		String retval = "";
		currentNode = currentNode.getNextSibling();
		currentNode = currentNode.getNextSibling();
		if (currentNode.getNodeName().equals("integer") || currentNode.getNodeName().equals("string") || currentNode.getNodeName().equals("date")) {
			retval = currentNode.getTextContent();
		}				 
		return retval;
	}
}
